import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Tabs, Toast, Dialog, Popup } from 'antd-mobile';
import axios from 'axios';
import { getUserInfo } from '../utils/auth';
import  {http,host,port} from '../utils/host'
// 定义接口
interface Dongtai {
  _id: string;
  userId: string;
  username: string;
  content: string;
  images?: string[];
  likeCount: number;
  commentCount: number;
  publishTime: string;
  // 根据实际数据结构添加其他字段
}

interface Topic {
  _id: string;
  name: string;
  description: string;
  hot: number;
  // 根据实际数据结构添加其他字段
}

interface UserInfo {
  _id: string;
  username: string;
  avatar?: string;
  // 根据实际数据结构添加其他字段
}

const TopicDetail: React.FC = () => {
  const { topicId } = useParams<{ topicId: string }>();
  const navigate = useNavigate();
  const [topicInfo, setTopicInfo] = useState<Topic | null>(null);
  const [hotDongtais, setHotDongtais] = useState<Dongtai[]>([]);
  const [latestDongtais, setLatestDongtais] = useState<Dongtai[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [activeTab, setActiveTab] = useState<'hot' | 'latest'>('hot');
  const currentUser = getUserInfo<UserInfo | null>();
  // 点赞状态
  const [likedDongtais, setLikedDongtais] = useState<Record<string, boolean>>({});
  // 评论功能状态
  const [showCommentDialog, setShowCommentDialog] = useState<boolean>(false);
  const [commentContent, setCommentContent] = useState<string>('');
  const [currentDongtaiId, setCurrentDongtaiId] = useState<string>('');
  // 分享功能状态
  const [showSharePopup, setShowSharePopup] = useState<boolean>(false);

  // 获取话题信息
  const fetchTopicInfo = async (): Promise<void> => {
    try {
      const response = await axios.get(`${http}${host}${port}/dongtai/getTopicInfo?topicId=${topicId}`);
      setTopicInfo(response.data);
    } catch (error) {
      console.error('获取话题信息失败:', error);
      Toast.show({ content: '获取话题信息失败', type: 'fail' });
    }
  };

  // 获取话题相关动态
  const fetchTopicDongtais = async (type: 'hot' | 'latest' = 'hot'): Promise<void> => {
    try {
      const response = await axios.get(
        `${http}${host}${port}/dongtai/getTopicDongtais?topicId=${topicId}&type=${type}`
      );
      if (type === 'hot') {
        setHotDongtais(response.data);
      } else {
        setLatestDongtais(response.data);
      }
    } catch (error) {
      console.error('获取话题动态失败:', error);
      Toast.show({ content: '获取话题动态失败', type: 'fail' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 先获取话题信息
    fetchTopicInfo();
    // 再获取动态
    fetchTopicDongtais(activeTab);
  }, [topicId, activeTab]);

  // 处理标签切换
  const handleTabChange = (tabKey: 'hot' | 'latest'): void => {
    setActiveTab(tabKey);
    setLoading(true);
  };

  // 处理参与讨论
  const handleJoinDiscussion = (): void => {
    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail' });
      return;
    }
    navigate('/publish', { state: { topicId, topicName: topicInfo?.name } });
  };

  // 处理点赞/取消点赞
  const handleLike = async (dongtaiId: string): Promise<void> => {
    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail' });
      return;
    }

    try {
      const isLiked = likedDongtais[dongtaiId] || false;
      const response = await axios.post(`${http}${host}${port}/dongtai/like`, {
        dongtaiId,
        like: !isLiked
      });

      // 更新点赞状态
      setLikedDongtais(prev => ({
        ...prev,
        [dongtaiId]: !isLiked
      }));

      // 更新动态列表中的点赞数量
      if (activeTab === 'hot') {
        setHotDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === dongtaiId) {
              return {
                ...item,
                likeCount: response.data.likeCount
              };
            }
            return item;
          });
        });
      } else {
        setLatestDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === dongtaiId) {
              return {
                ...item,
                likeCount: response.data.likeCount
              };
            }
            return item;
          });
        });
      }

      Toast.show({ content: isLiked ? '已取消点赞' : '点赞成功', type: 'success' });
    } catch (error) {
      console.error('点赞操作失败:', error);
      Toast.show({ content: '操作失败，请重试', type: 'fail' });
    }
  };

  // 打开评论对话框
  const openCommentDialog = (dongtaiId: string): void => {
    setCurrentDongtaiId(dongtaiId);
    setCommentContent('');
    setShowCommentDialog(true);
  };

  // 关闭评论对话框
  const closeCommentDialog = (): void => {
    setShowCommentDialog(false);
  };

  // 提交评论
  const submitComment = async (): Promise<void> => {
    if (!commentContent.trim()) {
      Toast.show({ content: '评论内容不能为空', type: 'fail' });
      return;
    }

    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail' });
      return;
    }

    try {
      const response = await axios.post(`${http}${host}${port}/dongtai/comment`, {
        dongtaiId: currentDongtaiId,
        content: commentContent,
        userId: currentUser._id,
        username: currentUser.username
      });

      // 更新动态列表中的评论数量
      if (activeTab === 'hot') {
        setHotDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === currentDongtaiId) {
              return {
                ...item,
                commentCount: response.data.commentCount
              };
            }
            return item;
          });
        });
      } else {
        setLatestDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === currentDongtaiId) {
              return {
                ...item,
                commentCount: response.data.commentCount
              };
            }
            return item;
          });
        });
      }

      closeCommentDialog();
      Toast.show({ content: '评论成功', type: 'success' });
    } catch (error) {
      console.error('评论操作失败:', error);
      Toast.show({ content: '评论失败，请重试', type: 'fail' });
    }
  };

  // 打开分享弹窗
  const openSharePopup = (dongtaiId: string): void => {
    setCurrentDongtaiId(dongtaiId);
    setShowSharePopup(true);
  };

  // 关闭分享弹窗
  const closeSharePopup = () => {
    setShowSharePopup(false);
  };

  // 执行分享操作
  const handleShare = async (type) => {
    try {
      // 更新分享计数
      const response = await axios.post(`${http}${host}${port}/dongtai/share`, {
        dongtaiId: currentDongtaiId
      });

      // 更新动态列表中的分享数量
      if (activeTab === 'hot') {
        setHotDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === currentDongtaiId) {
              return {
                ...item,
                shareCount: response.data.shareCount
              };
            }
            return item;
          });
        });
      } else {
        setLatestDongtais(prevList => {
          return prevList.map(item => {
            if (item._id === currentDongtaiId) {
              return {
                ...item,
                shareCount: response.data.shareCount
              };
            }
            return item;
          });
        });
      }

      // 生成分享链接
      const shareUrl = `${http}${host}${port}/dongtai/${currentDongtaiId}`;
      const shareTitle = '分享一条动态';

      // 根据分享类型执行不同操作
      switch (type) {
        case 'wechat':
          // 微信分享
          if (window.wx) {
            wx.showMenuItems({
              menuList: ['menuItem:share:appMessage'], // 分享给朋友
            });
            wx.onMenuShareAppMessage({
              title: shareTitle,
              link: shareUrl,
              imgUrl: '${http}${host}${port}/logo.png',
              success: function() {
                Toast.show({ content: '微信分享成功', type: 'success' });
              },
              cancel: function() {
                Toast.show({ content: '取消微信分享', type: 'none' });
              }
            });
          } else {
            // 没有微信SDK时，提供复制链接方案
            await navigator.clipboard.writeText(shareUrl);
            Toast.show({ content: '链接已复制，请在微信中粘贴分享', type: 'success' });
          }
          break;
        case 'weibo':
          // 微博分享
          const weiboShareUrl = `http://service.weibo.com/share/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(shareTitle)}`;
          window.open(weiboShareUrl, '_blank');
          Toast.show({ content: '正在跳转到微博', type: 'success' });
          break;
        case 'copy':
          // 复制链接到剪贴板
          await navigator.clipboard.writeText(shareUrl);
          Toast.show({ content: '分享链接已复制到剪贴板', type: 'success' });
          break;
        case 'more':
          // 更多分享选项
          if (navigator.share) {
            navigator.share({
              title: shareTitle,
              url: shareUrl
            }).then(() => {
              Toast.show({ content: '分享成功', type: 'success' });
            }).catch((err) => {
              console.error('分享失败:', err);
              Toast.show({ content: '分享失败', type: 'fail' });
            });
          } else {
            await navigator.clipboard.writeText(shareUrl);
            Toast.show({ content: '链接已复制，请手动分享', type: 'success' });
          }
          break;
        default:
          await navigator.clipboard.writeText(shareUrl);
          Toast.show({ content: '分享链接已复制到剪贴板', type: 'success' });
      }

      closeSharePopup();
    } catch (error) {
      console.error('分享操作失败:', error);
      Toast.show({ content: '分享失败，请重试', type: 'fail' });
    }
  };

  // 监听点赞状态
  useEffect(() => {
    // 初始化点赞状态
    const initLikedState = () => {
      const likedState = {};
      if (activeTab === 'hot') {
        hotDongtais.forEach(dongtai => {
          likedState[dongtai._id] = dongtai.isLiked || false;
        });
      } else {
        latestDongtais.forEach(dongtai => {
          likedState[dongtai._id] = dongtai.isLiked || false;
        });
      }
      setLikedDongtais(likedState);
    };

    initLikedState();
  }, [hotDongtais, latestDongtais, activeTab]);

  // 格式化时间差
  const formatTimeDifference = (publishTime) => {
    if (!publishTime) return '';

    const now = new Date();
    const publishDate = new Date(publishTime);
    const diffInSeconds = Math.floor((now - publishDate) / 1000);

    // 计算不同时间单位的差值
    const secondsInMinute = 60;
    const secondsInHour = secondsInMinute * 60;
    const secondsInDay = secondsInHour * 24;
    const secondsInMonth = secondsInDay * 30;
    const secondsInYear = secondsInDay * 365;

    if (diffInSeconds < secondsInMinute) {
      return `${diffInSeconds}秒前`;
    } else if (diffInSeconds < secondsInHour) {
      return `${Math.floor(diffInSeconds / secondsInMinute)}分钟前`;
    } else if (diffInSeconds < secondsInDay) {
      return `${Math.floor(diffInSeconds / secondsInHour)}小时前`;
    } else if (diffInSeconds < secondsInMonth) {
      return `${Math.floor(diffInSeconds / secondsInDay)}天前`;
    } else if (diffInSeconds < secondsInYear) {
      return `${Math.floor(diffInSeconds / secondsInMonth)}个月前`;
    } else {
      return `${Math.floor(diffInSeconds / secondsInYear)}年前`;
    }
  };

  if (loading && !topicInfo) {
    return <div className="loading-container">加载中...</div>;
  }

  return (
    <div className="topic-detail-container">
      {/* 头部返回按钮和标题 */}
      <div className="header">
        <button className="back-btn" onClick={() => navigate(-1)}>
          <i className="icon-back"></i> 返回
        </button>
        <h1 className="title">话题详情</h1>
        <div className="right-space"></div>
      </div>

      {/* 话题信息 */}
      <div className="topic-info">
        <div className="topic-banner">
          <div className="topic-name-container">
            <h2 className="topic-name">{topicInfo?.name}</h2>
            <p className="topic-view-count">{topicInfo?.viewCount || 0}次浏览</p>
          </div>
        </div>
        <p className="topic-description">{topicInfo?.description || '暂无描述'}</p>
      </div>

      {/* 标签切换 */}
      <Tabs
        activeKey={activeTab}
        onChange={handleTabChange}
        className="topic-tabs"
      >
        <Tabs.Tab key="hot" title="热门" />
        <Tabs.Tab key="latest" title="最新" />
      </Tabs>

      {/* 动态列表 */}
      <div className="dongtai-list">
        {loading ? (
          <div className="loading-container">加载中...</div>
        ) : activeTab === 'hot' ? (
          hotDongtais.length > 0 ? (
            hotDongtais.map((dongtai) => (
              <div key={dongtai._id} className="dongtai-item">
                <div className="user-info">
                  <img
                    src={dongtai.user.avatarImage || 'default-avatar.png'}
                    alt=""
                    className="avatar"
                    onClick={() => navigate(`/user-detail/${dongtai.user._id}`)}
                    onError={(e) => {
                      // 如果本地存储的头像加载失败，回退到默认头像
                      (e.target as HTMLImageElement).src = "";
                    }}
                  />
                  <div className="user-name-container">
                    <p className="user-name" onClick={() => navigate(`/user-detail/${dongtai.user._id}`)}>{dongtai.user.username || dongtai.user._id}</p>
                    <p className="post-time">{formatTimeDifference(dongtai.createdAt)}</p>
                  </div>
                </div>
                <p className="content">{dongtai.title || dongtai.content}</p>
                {dongtai.media && dongtai.media.length > 0 && (
                    <div className="image-container">
                      {dongtai.media.map((url, index) => {
                        // 检查文件扩展名以确定媒体类型
                        const isVideo = url.match(/\.(mp4|mov|webm|avi|mkv)$/i);
                        const mediaUrl = `${http}${host}${port}` + url;

                        if (isVideo) {
                          return (
                            <video
                              key={index}
                              src={mediaUrl}
                              alt=""
                              className="dongtai-image"
                              controls
                              loop
                              muted
                              playsInline
                            />
                          );
                        } else {
                          return (
                            <img
                              key={index}
                              src={mediaUrl}
                              alt={`动态图片${index + 1}`}
                              className="dongtai-image"
                            />
                          );
                        }
                      })}
                    </div>
                  )}
                <div className="topic-tag">
                  <span>#{topicInfo?.name}</span>
                </div>
                <div className="action-bar">
                    <button className="action-btn share-btn" onClick={() => openSharePopup(dongtai._id)}>
                      🔄 {dongtai.shareCount || 0}
                    </button>
                    <button className="action-btn comment-btn" onClick={() => openCommentDialog(dongtai._id)}>
                      💬 {dongtai.commentCount || 0}
                    </button>
                    <button className="action-btn like-btn" onClick={() => handleLike(dongtai._id)} style={{ color: likedDongtais[dongtai._id] ? '#FF6B6B' : '#333' }}>
                      👍 {dongtai.likeCount || 0}
                    </button>
                  </div>
              </div>
            ))
          ) : (
            <div className="empty-tip">暂无热门动态</div>
          )
        ) : (
          latestDongtais.length > 0 ? (
            latestDongtais.map((dongtai) => (
              <div key={dongtai._id} className="dongtai-item">
                <div className="user-info">
                  <img
                    src={dongtai.user.avatarImage || 'default-avatar.png'}
                    alt=""
                    className="avatar"
                    onClick={() => navigate(`/user-detail/${dongtai.user._id}`)}
                    onError={(e) => {
                      // 如果本地存储的头像加载失败，回退到默认头像
                      (e.target as HTMLImageElement).src = "";
                    }}
                  />
                  <div className="user-name-container">
                    <p className="user-name" onClick={() => navigate(`/user-detail/${dongtai.user._id}`)}>{dongtai.user.username || dongtai.user._id}</p>
                    <p className="post-time">{formatTimeDifference(dongtai.createdAt)}</p>
                  </div>
                </div>
                <p className="content">{dongtai.title || dongtai.content}</p>
                {dongtai.media && dongtai.media.length > 0 && (
                    <div className="image-container">
                      {dongtai.media.map((url, index) => {
                        // 检查文件扩展名以确定媒体类型
                        const isVideo = url.match(/\.(mp4|mov|webm|avi|mkv)$/i);
                        const mediaUrl = `${http}${host}${port}` + url;

                        if (isVideo) {
                          return (
                            <video
                              key={index}
                              src={mediaUrl}
                              alt=""
                              className="dongtai-image"
                              controls
                              loop
                              muted
                              playsInline
                            />
                          );
                        } else {
                          return (
                            <img
                              key={index}
                              src={mediaUrl}
                              alt={`动态图片${index + 1}`}
                              className="dongtai-image"
                            />
                          );
                        }
                      })}
                    </div>
                  )}
                <div className="topic-tag">
                  <span>#{topicInfo?.name}</span>
                </div>
                <div className="action-bar">
                    <button className="action-btn share-btn" onClick={() => openSharePopup(dongtai._id)}>
                      🔄 {dongtai.shareCount || 0}
                    </button>
                    <button className="action-btn comment-btn" onClick={() => openCommentDialog(dongtai._id)}>
                      💬 {dongtai.commentCount || 0}
                    </button>
                    <button className="action-btn like-btn" onClick={() => handleLike(dongtai._id)} style={{ color: likedDongtais[dongtai._id] ? '#FF6B6B' : '#333' }}>
                      👍 {dongtai.likeCount || 0}
                    </button>
                  </div>
              </div>
            ))
          ) : (
            <div className="empty-tip">暂无最新动态</div>
          )
        )}
      </div>

      {/* 参与讨论按钮 */}
      <button className="join-discussion-btn" onClick={handleJoinDiscussion}>
        参与话题讨论
      </button>

      {/* 评论对话框 */}
      <Dialog
        visible={showCommentDialog}
        onClose={closeCommentDialog}
        title="发表评论"
        confirmText="发送"
        onConfirm={submitComment}
        cancelText="取消"
        onCancel={closeCommentDialog}
      >
        <div style={{ padding: '10px 0' }}>
          <textarea
            style={{ width: '100%', padding: '10px', border: '1px solid #ddd', borderRadius: '6px', fontSize: '14px', resize: 'none', boxSizing: 'border-box' }}
            placeholder="写下你的评论..."
            value={commentContent}
            onChange={(e) => setCommentContent(e.target.value)}
            rows={4}
          />
        </div>
      </Dialog>

      {/* 分享功能Popup */}
      <Popup
        visible={showSharePopup}
        onClose={closeSharePopup}
        position="bottom"
        bodyStyle={{ height: 'auto', padding: '24px 0 16px' }}
        closeOnMaskClick={true}
      >
        <div className="share-popup-header">
          <h3 className="share-title">立即分享给好友</h3>
        </div>
        <div className="share-options">
          <div className="share-option" onClick={() => handleShare('wechat')}>
            <div className="share-icon">🟢</div>
            <div className="share-text">微信</div>
          </div>
          <div className="share-option" onClick={() => handleShare('weibo')}>
            <div className="share-icon">🔴</div>
            <div className="share-text">微博</div>
          </div>
          <div className="share-option" onClick={() => handleShare('copy')}>
            <div className="share-icon">🔗</div>
            <div className="share-text">复制链接</div>
          </div>
          <div className="share-option" onClick={() => handleShare('more')}>
            <div className="share-icon">📤</div>
            <div className="share-text">分享</div>
          </div>
        </div>
        <div className="share-cancel" onClick={closeSharePopup}>
          <span className="cancel-text">取消</span>
        </div>
      </Popup>

      <style>{`
        .topic-detail-container {
          min-height: 100vh;
          background-color: #f5f5f5;
          padding-bottom: 70px;
        }

        .header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 50px;
          padding: 0 15px;
          background-color: #fff;
          border-bottom: 1px solid #eee;
          position: sticky;
          top: 0;
          z-index: 10;
        }

        .back-btn {
          background: none;
          border: none;
          font-size: 18px;
          color: #333;
          padding: 5px;
        }

        .title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin: 0;
        }

        .right-space {
          width: 40px;
        }

        .topic-info {
          background-color: #fff;
          padding: 15px;
          margin-bottom: 10px;
        }

        .topic-banner {
          position: relative;
          height: 80px;
          border-radius: 8px;
          overflow: hidden;
          margin-bottom: 15px;
          background-color: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .topic-name-container {
          text-align: center;
          padding: 15px;
          color: #333;
        }

        .topic-name {
          font-size: 20px;
          font-weight: bold;
          margin: 0 0 5px 0;
        }

        .topic-view-count {
          font-size: 14px;
          margin: 0;
        }

        .topic-description {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
          margin: 0;
        }

        .topic-tabs {
          background-color: #fff;
          margin-bottom: 10px;
        }

        .dongtai-list {
          padding: 0 15px;
        }

        .dongtai-item {
          background-color: #fff;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 10px;
        }

        .user-info {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
        }

        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          object-fit: cover;
          margin-right: 10px;
        }

        .user-name-container {
          flex: 1;
        }

        .user-name {
          font-size: 14px;
          font-weight: bold;
          color: #333;
          margin: 0;
        }

        .post-time {
          font-size: 12px;
          color: #999;
          margin: 0;
        }

        .content {
          font-size: 16px;
          color: #333;
          margin: 0 0 10px 0;
          line-height: 1.5;
        }

        .image-container {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 10px;
        }

        .dongtai-image {
          width: 32%;
          height: 100px;
          object-fit: cover;
          border-radius: 4px;
          margin-right: 2%;
          margin-bottom: 2%;
        }

        .dongtai-image:nth-child(3n) {
          margin-right: 0;
        }

        .topic-tag {
          display: inline-block;
          background-color: #f0f0f0;
          color: #666;
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
          margin-bottom: 10px;
        }

        .action-bar {
          display: flex;
          justify-content: space-between;
          padding-top: 10px;
          border-top: 1px solid #f0f0f0;
        }

        .action-btn {
          background: none;
          border: none;
          color: #999;
          font-size: 14px;
          display: flex;
          align-items: center;
        }

        .icon-share, .icon-comment, .icon-like {
          margin-right: 5px;
        }

        /* 移除不再使用的liked类样式 */
        /* .liked {
          color: #FF6B6B;
        } */

        .join-discussion-btn {
          position: fixed;
          bottom: 20px;
          left: 50%;
          transform: translateX(-50%);
          width: 80%;
          height: 45px;
          background-color: #ff6b6b;
          color: #fff;
          border: none;
          border-radius: 22.5px;
          font-size: 16px;
          font-weight: bold;
          box-shadow: 0 4px 10px rgba(255, 107, 107, 0.3);
        }

        /* 分享弹窗样式 */
        .share-popup-header {
          text-align: center;
          margin-bottom: 20px;
        }
        .share-title {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin: 0;
        }
        .share-options {
          display: flex;
          justify-content: space-around;
          padding: 0 20px;
          margin-bottom: 30px;
        }
        .share-option {
          display: flex;
          flex-direction: column;
          align-items: center;
          cursor: pointer;
        }
        .share-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          background-color: #F8F9FA;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          margin-bottom: 8px;
        }
        .share-text {
          font-size: 12px;
          color: #666;
        }
        .share-cancel {
          text-align: center;
          padding: 12px 0;
          border-top: 1px solid #F0F0F0;
          cursor: pointer;
        }
        .cancel-text {
          font-size: 16px;
          color: #FF6B6B;
          font-weight: bold;
        }

        .loading-container {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100px;
          color: #999;
        }

        .empty-tip {
          text-align: center;
          padding: 30px 0;
          color: #999;
        }
      `}</style>
    </div>
  );
};

export default TopicDetail;